package com.york.security.security;

import com.york.utils.exception.result.R;
import com.york.utils.util.ResponseUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Description:退出处理器
 * @Data: 2022/3/22 15:38
 * @Author: yangboxiong
 * @Version
 * @since JDK 1.8
 */
@Slf4j
public class TokenLogoutHandler implements LogoutHandler {

    private JwtUtils jwtUtils;

    private RedisTemplate redisTemplate;

    public TokenLogoutHandler(JwtUtils jwtUtils, RedisTemplate redisTemplate) {
        this.jwtUtils = jwtUtils;
        this.redisTemplate = redisTemplate;
    }

    /**
     * 退出登录
     *
     * @param request
     * @param response
     * @param authentication
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
        //1、从header 中获取token
        //2、如果token 不为空，就移除 token，在从 redis中删除 token
        String token = request.getHeader("token");
        log.info("获取请求的token值:{}", token);
        if (token != null) {
            //移除token
            JwtUtils.removeToken(token);
            // 从token中获取用户名
            String userName = JwtUtils.getUserName(token);
            // 从 redis 中移除掉 token
            redisTemplate.delete(userName);
        }
        ResponseUtil.out(response, R.ok());
    }
}
